import NavBar from '@/components/NavBar';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import styles from './index.module.scss';
import { useEffect, useRef, useState } from 'react';
import { useAppDispatch, useAppSelector } from '@/store';
import { getUserAction, updateUserProfileAction, uploadPhotoAction } from '@/store/action/user';
import { userType } from '@/store/reducer/user';
import Input from '@/components/Input';
import Textarea from '@/components/Textarea';
import dayjs from 'dayjs';
import { PickerDate } from 'antd-mobile/es/components/date-picker/util';
import { removeAuth } from '@/utils/storage';
import { useHistory } from 'react-router-dom';
type editType = 'photo' | 'gender' | 'name' | 'intro';
export default function ProfileEdit() {
  const history = useHistory();
  const iptRef = useRef<HTMLInputElement>(null);
  const dispatch = useAppDispatch();
  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [birthVisible, setBirthVisible] = useState(false);
  const [editType, setEditType] = useState('' as editType);
  const [name, setName] = useState('');
  const [intro, setIntro] = useState('');

  const { user } = useAppSelector((state) => state.user);
  //回显名字
  useEffect(() => {
    setName(user.name);
    setIntro(user.intro || '');
  }, [user]);

  const handleInputClick = () => {
    if (iptRef.current) {
      iptRef.current.click();
    }
  };
  //返回退出弹出层
  const handleCancel = () => {
    setRightVisible(false);
    setName(user.name);
    setIntro(user.intro || '');
  };
  //上传头像
  const handUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const formData = new FormData();
      formData.append('photo', file);
      // 第一种写法通过调用dispatch方法，触发action 更新redux中的数据
      await dispatch(uploadPhotoAction(formData));
      // 第二种写法，直接调用getUserAction重新获取数据
      handleRefrsh();
    }
  };
  //通用刷新函数
  const handleRefrsh = async () => {
    await dispatch(getUserAction());
    Toast.show({ content: '更新成功', icon: 'success' });
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
  };
  //通用弹出层函数
  const handleEditShow = (type: editType) => {
    setEditType(type);
    if (type === 'name' || type === 'intro') {
      setRightVisible(true);
    } else {
      setVisible(true);
    }
  };
  //通用的更新数据函数
  const handleUpdateProfile = (data: Partial<userType>) => {
    dispatch(updateUserProfileAction(data));
    handleRefrsh();
  };
  //提交
  const handleSubmit = (obj: Partial<userType>) => {
    handleUpdateProfile(obj);
  };
  const renderPhotoOrGender = () => {
    if (editType === 'photo') {
      return (
        <>
          <div className="list-item" onClick={handleInputClick}>
            拍照
          </div>
          <div className="list-item" onClick={handleInputClick}>
            本地选择
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }
    if (editType === 'gender') {
      return (
        <>
          <div className="list-item" onClick={() => handleUpdateProfile({ gender: 0 })}>
            男
          </div>
          <div className="list-item" onClick={() => handleUpdateProfile({ gender: 1 })}>
            女
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }
  };

  const renderNameOrIntro = () => {
    const obj = {} as Partial<userType>;
    if (editType === 'name') {
      obj.name = name;
    }
    if (editType === 'intro') {
      obj.intro = intro;
    }
    return (
      <>
        <NavBar
          onBack={handleCancel}
          right={
            <span onClick={() => handleSubmit(obj)} className="submit-btn">
              提交
            </span>
          }
        >
          编辑用户信息
        </NavBar>
        <div className="edit-content">
          <h3 className="edit-title">编辑{editType === 'name' ? '昵称' : '简介'}</h3>
          {editType === 'name' && (
            <Input autoFocus value={name} onChange={(e) => setName(e.target.value)} className="edit-input" />
          )}
          {editType === 'intro' && (
            <Textarea autoFocus value={intro} onChange={(e) => setIntro(e.target.value)}></Textarea>
          )}
        </div>
      </>
    );
  };
  const handleBirthSubmit = (val: PickerDate) => {
    handleUpdateProfile({ birthday: dayjs(val).format('YYYY-MM-DD') });
  };
  // 退出登录
  const handleLogout = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要退出吗',
      onConfirm: () => {
        // 清理本地存储的 Token 信息
        removeAuth();
        // 跳转到登录页
        history.push('/login');
        // 提示
        Toast.show({ content: '退出登录成功' });
      },
    });
  };
  useEffect(() => {
    dispatch(getUserAction());
  }, []);
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              onClick={() => handleEditShow('photo')}
              arrow
              extra={<img className="avatar" src={user.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item onClick={() => handleEditShow('name')} arrow extra={user.name}>
              昵称
            </List.Item>

            <List.Item
              onClick={() => handleEditShow('intro')}
              arrow
              extra={<span className="intro">{user.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item onClick={() => handleEditShow('gender')} arrow extra={user.gender ? '女' : '男'}>
              性别
            </List.Item>
            <List.Item onClick={() => setBirthVisible(true)} arrow extra={user.birthday}>
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input ref={iptRef} onChange={handUpload} className="avatar-upload" type="file" />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout" onClick={handleLogout}>
          <button className="btn">退出登录</button>
        </div>
      </div>
      {/* 底部弹出层 */}
      <Popup
        visible={visible}
        position="bottom"
        bodyClassName="popup-bottom-list"
        onMaskClick={() => setVisible(false)}
      >
        {renderPhotoOrGender()}
      </Popup>
      {/* 右侧弹出层 */}
      <Popup
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
        onMaskClick={() => setRightVisible(false)}
        destroyOnClose
      >
        {renderNameOrIntro()}
      </Popup>
      <DatePicker
        title="选择生日"
        visible={birthVisible}
        onClose={() => {
          setBirthVisible(false);
        }}
        min={new Date('1900-01-01')}
        max={new Date()}
        value={new Date(user.birthday)}
        onConfirm={(val) => handleBirthSubmit(val)}
      />
    </div>
  );
}
